//var port = chrome.extension.connect({name: "defChannel"});
//port.postMessage({query: "test"});
var bubbleX, bubbleY = 100;
var mouseTarget;
/*var mod = localStorage["mod"];
if(!mod)mod = 16;
var smod = localStorage["smod"];
if(!smod)mod = -1;
var key = localStorage["key"];
if(!key)key = 68;*/
var mod = 16;
var smod = -1;
var key = 68;
document.body.onmouseup = function(e){
	removeBubble();
	bubbleX = e.screenX-70;
	bubbleY = e.screenY-50;
	if(bubbleX + 400 > window.innerWidth)bubbleX = window.innerWidth - 470; 
	if(bubbleY + 500 > window.innerHeight)bubbleY = window.innerHeight - 550; 
	console.log(bubbleY);
	console.log(bubbleX);
}

var ctrldown = false;
document.onkeyup = function(e){
    if(e.which == mod)ctrldown=false;
}

document.onkeydown = function(e){
    if(e.which == mod)ctrldown = true;
    if(e.which == key && ctrldown){
        console.log("jou");
        if(window.getSelection){
            var text = window.getSelection().toString();
            console.log(text);
            if(text != null && text != ""){
                  var port = chrome.extension.connect({name: "defChannel"});
                  port.postMessage({query: text});
            }
        }

    
    }
}

function show_bubble(text){

      var bubble = document.createElement("div");
      //bubble.id = "defbubble";
      bubble.setAttribute("class", "defbubble");
      bubble.style.top = bubbleY.toString() + "px";
      bubble.style.left = bubbleX.toString() + "px";
      //bubble.setAttribute("class", "infobubble");
      var temp = document.createElement("div");
      temp.innerHTML = text.toString();
      list = temp.getElementsByClassName("std");	
      if(list != null){
            list = list[0];
            list.setAttribute("class", "deful");
            list = list.getElementsByTagName("li");
            for(var i = 0; i < 3; i++)bubble.appendChild(list[i]);
        
      }
      document.body.appendChild(bubble);

}
chrome.extension.onConnect.addListener(function(port){
//    console.log("Message received");
	if(port.name == "defbuttonClicked"){
		port.onMessage.addListener(function(msg){
			if(msg.buttonClicked){
			  console.log("PING!");
			  if(window.getSelection){
				  var text = window.getSelection().toString();
				  if(text != null && text != ""){
					  //console.log(window.getSelection().focusNode);
					  var port2 = chrome.extension.connect({name: "defChannel"});
					  port2.postMessage({query: text});
				  }
			  }

			}
		});
	}
	else if(port.name=="defResponse"){
		port.onMessage.addListener(function(msg){
			console.log("PONG");
			if(msg.text){
              show_bubble(msg.text);
			   
			}
		});


	}
});
function removeBubble(){
	var bubbles = document.getElementsByClassName("defbubble");
	if(bubbles != null){
		for(var i= 0; i < bubbles.length; i++){
			document.body.removeChild(bubbles[i]);
		}
	}
}
